package com.sicau.basedemo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sicau.basedemo.common.myenum.UserTypeEnum;
import com.sicau.basedemo.common.returning.ResultData;
import com.sicau.basedemo.config.aop.ValidateAspect;
import com.sicau.basedemo.entity.param.user.UserAddParam;
import com.sicau.basedemo.entity.param.user.UserLoginParam;
import com.sicau.basedemo.entity.param.user.UserQueryParam;
import com.sicau.basedemo.entity.po.User;
import com.sicau.basedemo.entity.vo.PageDataVO;
import com.sicau.basedemo.entity.vo.user.UserTypeVO;
import com.sicau.basedemo.entity.vo.user.UserVO;
import com.sicau.basedemo.service.UserService;
import com.sicau.basedemo.util.MD5Util;
import com.sicau.basedemo.util.UUIDUtils;
import com.sicau.basedemo.util.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import static com.sicau.basedemo.common.constant.UrlConstants.USER_PREFIX;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author sxt && ttxxi
 * @since 2021-04-26
 */
@RestController
@RequestMapping(USER_PREFIX)
@Slf4j
@Api(tags = "用户相关")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public ResultData<Boolean> login(UserLoginParam param){
        log.info("------------------------aaaaa");
        Boolean res = userService.userLogin(param);
        return new ResultData<Boolean>()
                .OK()
                .setResultIns("hahahah")
                .setObj(res);
    }

    @PostMapping
    @ApiOperation(value = "新增用户信息记录")
    @ValidateAspect.ParamValidate()
    public ResultData<Boolean> addTraceInfo(
            @RequestBody @Valid UserAddParam userAddParam,
            @ApiParam(hidden = true) @SuppressWarnings("unused") BindingResult bindingResult) {

        //账号重复性判断
        int count = userService.count(new LambdaQueryWrapper<User>().eq(User::getNumber, userAddParam.getNumber()));
        if (count > 0) {
            log.info("用户信息添加失败, 账号信息已存在");
            return new ResultData<Boolean>()
                    .FAILED()
                    .setResultIns("用户信息添加失败, 账号信息已存在")
                    .setObj(Boolean.FALSE);
        }

        //数据整理
        User tmpUser = new User();
        BeanUtils.copyProperties(userAddParam, tmpUser);
        String salt = UUIDUtils.getCode();
        tmpUser.setSalt(salt)
                .setPassword(MD5Util.encode(tmpUser.getPassword() + salt));


        log.info("新增用户信息记录操作, 用户信息: {}", tmpUser);

        //添加操作
        boolean rs = userService.save(tmpUser);

        //结果返回
        if (rs) {
            log.info("用户信息添加成功");

            return new ResultData<Boolean>()
                    .OK()
                    .setResultIns("用户信息添加成功")
                    .setObj(Boolean.TRUE);
        } else {
            log.info("用户信息添加失败");
            return new ResultData<Boolean>()
                    .FAILED()
                    .setResultIns("用户信息添加失败")
                    .setObj(Boolean.FALSE);
        }

    }

    @GetMapping
    @ApiOperation(value = "查询用户信息(传入条件则根据条件查询, 否则查询全部数据)")
    public ResultData<PageDataVO<UserVO>> getUsers(UserQueryParam userQueryParam) {
        log.info("查询用户信息");
        return new ResultData<PageDataVO<UserVO>>().OK().setObj(userService.queryUsersByCondition(userQueryParam));
    }

    @GetMapping("{id}")
    @ApiOperation(value = "根据用户id查询用户信息")
    public ResultData<UserVO> getUserById(@PathVariable Integer id) {
        log.info("根据用户id查询用户信息");
        return new ResultData<UserVO>().OK().setObj(userService.queryUsersById(id));
    }

    @GetMapping("/type/{number}")
    @ApiOperation(value = "根据学号获取用户类型")
    public ResultData<UserTypeVO> getUserType(@PathVariable Integer number) {
        log.info("根据学号获取用户类型");
        User user = userService.queryUserByNumber(number);
        if (ObjectUtils.isEmpty(user)){
            return new ResultData().FAILED().setResultIns("学号错误");
        }
        UserTypeVO userTypeVO = new UserTypeVO();
        userTypeVO.setTypeCode(user.getUserType());
        userTypeVO.setType(UserTypeEnum.getTypeByCode(user.getUserType()));
        return new ResultData<UserTypeVO>().OK().setObj(userTypeVO);
    }



    @GetMapping("/current")
    @ApiOperation(value = "获取当前用户信息")
    public ResultData<UserVO> getCurrentUsers() {
        log.info("查询当前用户信息");
        return new ResultData<UserVO>().OK().setObj(userService.queryById(UserContext.get().getId()));
    }

    /*=========================================华丽的分割线==============================================*/

    /**
     * 访问禁止需要授权提示信息
     *
     * @return 访问禁止需要授权提示信息
     */
    @ApiOperation(value = "访问禁止需要授权提示信息", hidden = true)
    @RequestMapping("/authentication/require")
    public ResultData<Boolean> requireAuthentication() {
        log.info("需要登录");
        return new ResultData<Boolean>()
                .FAILED()
                .setResultIns("需要登录")
                .setObj(Boolean.FALSE);
    }



}

